package com.cgutech.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.ReferenceCountUtil;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class NettyServer {
    private int port;
    private ChannelFuture channelFuture = null;
    private Map<String, ChannelHandlerContext> channelHandlerContextMap = new ConcurrentHashMap<>();
    public NettyServer(int port) {
        this.port = port;
    }

    public void doWork() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {

            ServerBootstrap sbs = new ServerBootstrap();
            sbs.group(group, workerGroup).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 2000)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            channelFuture = sbs.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public void close() {
        if(channelFuture != null) {
            channelFuture.channel().close();
        }
    }

    public void broadCast(byte[] data) {
        for(Map.Entry<String, ChannelHandlerContext> entry : channelHandlerContextMap.entrySet()) {
            entry.getValue().channel().writeAndFlush(Unpooled.copiedBuffer(data));
        }
    }

    private class NettyServerHandler extends ChannelInboundHandlerAdapter {
        /**
         * 客户端连接
         */
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            Channel channel = ctx.channel();
            String address = channel.remoteAddress().toString();
            channelHandlerContextMap.put(address, ctx);
            System.out.println("客户端[" + address + "]连接, 客户端连接数量[" + channelHandlerContextMap.size() + "]");
        }

        /**
         * 客户连接断开
         */
        @Override
        public synchronized void channelInactive(ChannelHandlerContext ctx) throws Exception {
            Channel channel = ctx.channel();
            String address = channel.remoteAddress().toString();
            channelHandlerContextMap.remove(address);
            System.out.println("客户端[" + address + "]连接断开, 客户端连接数量[" + channelHandlerContextMap.size() + "]");
        }

        /**
         * 客户端数据
         */
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            Channel channel = ctx.channel();
            try {
                ByteBuf bb = (ByteBuf) msg;
                byte[] respByte = new byte[bb.readableBytes()];
                bb.getBytes(0, respByte);
                System.out.println("客户端[" + channel.remoteAddress().toString() + "]数据: " + new String(respByte));
                channel.writeAndFlush(Unpooled.copiedBuffer(respByte));
            } finally {
                ReferenceCountUtil.release(msg);
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            Channel channel = ctx.channel();
            String address = channel.remoteAddress().toString();
            channelHandlerContextMap.remove(address);
            System.out.println("客户端[" +address + "]异常");
            cause.printStackTrace();
        }
    }
}
